package top.infopub.mgr.mkt.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.mkt.PlotDetailDto;
import top.infopub.enums.mkt.ProProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.enums.mkt.ProjectFormatEnum;
import top.infopub.enums.sg.CoopInfoTypesEnums;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.cnst.FlowTemplateEnum;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.*;
import top.infopub.mgr.mkt.domain.ProjectDomain;
import top.infopub.mgr.mkt.domain.SetupProDomain;
import top.infopub.mgr.mkt.jsonvo.SetupJsonVo;
import top.infopub.mgr.mkt.service.BaseLineService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.mgr.mkt.vo.*;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.model.common.MktSetupProInfo;
import top.infopub.model.mkt.*;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.DateUtil;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class SetupProServiceImpl extends GenericServiceImpl<SetupPro, String> implements
		SetupProService {

	@Autowired
	private SetupProDao setupProDao;

	@Autowired
    private SetupProCoopDao setupProCoopDao;

    @Autowired
    private SetupProSubDao setupProSubDao;

    @Autowired
    private SetupProAttDao setupProAttDao;

    @Autowired
    private AfterSummaryCoopDao afterSummaryCoopDao;

    @Autowired
    private ProjectSubInfoDao projectSubInfoDao;

    @Autowired
    private ProjectRiskDao projectRiskDao;

    @Autowired
    private PlotInfoDao plotInfoDao;

    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;

    @Autowired
    private ProjectInfoDao projectInfoDao;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private BaseLineService baseLineService;

	@Autowired
    private WsFlowProcessService wsFlowProcess;

	@Autowired
    private ProProcessManageService proProcessManageService;

	@Autowired
    private OAFlowService oaFlowService;

	@Override
	public GenericDao<SetupPro, String> getDao() {
		return setupProDao;
	}

    @Override
    public Page<ProjectDomain> selectPageByDomainWhere(Page<ProjectDomain> page,
                                                       CollectProjectVo collectProjectVo) throws ParseException {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        //处理时间范围
        if (!StringUtils.isEmpty(collectProjectVo.getDates()))
        {
            String[] splitTime = collectProjectVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            collectProjectVo.setStartDate(format.parse(splitTime[0]));
            collectProjectVo.setEndDate(format.parse(splitTime[1]));
        }
        return (Page<ProjectDomain>)setupProDao.selectByDomainWhere(collectProjectVo);
    }

    @Override
    public Page<SetupProDomain> selectMyCheckByDomainWhere(Page<SetupProDomain> page,
                                                           SetupProVo setupProVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<SetupProDomain>)setupProDao.selectMyCheckByDomainWhere(setupProVo);
    }

    @Override
    public SetupProVo selectById(String id) {
        return setupProDao.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSetupPro(SetupPro setupPro, List<SetupProCoop> setupProCoops,
                            List<SetupProSub> setupProSubs, List<SetupProAtt> setupProAtts) {
        //插入预立项记录
        setupProDao.insertById(setupPro);

        //批量插入联合体单位
        if(CollectionUtils.isNotEmpty(setupProCoops)){
            setupProCoopDao.insertByBatch(setupProCoops);
        }

        //批量插入子项
        if(CollectionUtils.isNotEmpty(setupProSubs)){
            setupProSubDao.insertByBatch(setupProSubs);
        }

        //批量插入附件
        if(CollectionUtils.isNotEmpty(setupProAtts)){
            setupProAttDao.insertByBatch(setupProAtts);
        }

        // 注意 这里根据不同的业务分支判断条件 获得不同enum
        FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_SETUP_PRO;
        // 处理工作流数据
        wsFlowProcess.launch(templateEnum, setupPro.getId(), setupPro.getProcessId(), null);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editSetupPro(SetupPro setupPro, List<SetupProCoop> setupProCoops, List<SetupProSub> setupProSubs, List<SetupProAtt> fileAtts,String submitType) {
        //编辑立项记录
        setupProDao.updateByIdSelective(setupPro);
        setupProCoopDao.deleteBySetupId(setupPro.getId());
        setupProSubDao.deleteBySetupId(setupPro.getId());
        setupProAttDao.deleteBySetupId(setupPro.getId());
        //批量插入联合体单位
        if(CollectionUtils.isNotEmpty(setupProCoops)){
            setupProCoopDao.insertByBatch(setupProCoops);
        }
        //批量插入子项
        if(CollectionUtils.isNotEmpty(setupProSubs)){
            setupProSubDao.insertByBatch(setupProSubs);
        }
        //批量插入附件
        if(CollectionUtils.isNotEmpty(fileAtts)){
            setupProAttDao.insertByBatch(fileAtts);
        }
        if("2".equalsIgnoreCase(submitType)){
            setupPro=setupProDao.selectById(setupPro.getId());
            SetupPro setup=new SetupPro();
            setup.setId(setupPro.getId());
            setup.setProcessStatus("1");//审判中
            setupProDao.updateByIdSelective(setup);
            // 注意 这里根据不同的业务分支判断条件 获得不同enum
            FlowTemplateEnum templateEnum = FlowTemplateEnum.MKT_SETUP_PRO;
            // 处理工作流数据
            wsFlowProcess.launch(templateEnum, setupPro.getId(), setupPro.getProcessId(), null);

        }
    }

    @Override
    public List<SetupPro> selectUsableSetupPro() {
        return setupProDao.selectUsableSetupPro();
    }

    @Override
    public List<SetupPro> selectByProCode(String proCode) {
        return setupProDao.selectByProCode(proCode);
    }

    @Override
    public SetupJsonVo queryDetailById(String id) {
        SetupJsonVo setupJson = new SetupJsonVo();
        //基础信息
        PlotDetailDto plotDetail = setupProDao.queryUnionDetailById(id);
        plotDetail.setDates(DateFormatUtils.format(new Date(), DateUtil.DATE_STYLE_SIMPLE));
        ProjectFormatEnum pfe = ProjectFormatEnum.getByCode(plotDetail.getProFormat());
        if (pfe != null) {
            plotDetail.setProFormat(pfe.getName());
        }
        setupJson.setInfo(plotDetail);
        //项目合作单位
        setupJson.setSummaryCoops(afterSummaryCoopDao.querySummaryCoopList(plotDetail.getProCode(), 0));
        //项目投资构成
        ProjectSubInfo projectSubInfo = projectSubInfoDao.queryByProCode(plotDetail.getProCode());
        if (projectSubInfo != null) {
            if (StringUtils.isNotBlank(projectSubInfo.getTitleJson())) {
                setupJson.setItemName(JSON.parseArray(projectSubInfo.getTitleJson(), ItemNameVo.class));
            }
            if (StringUtils.isNotBlank(projectSubInfo.getContentJson())) {
                setupJson.setInvestmentInfoVos(JSON.parseArray(projectSubInfo.getContentJson(), InvestmentInfoVo.class));
            }
        }
        //项目风险信息
        setupJson.setRiskTable(projectRiskDao.selectByProCode(plotDetail.getProCode()));
        //底线标准情况
        setupJson.setStandardTable(baseLineService.checkIsSatisfy(plotDetail.getProCode()));
        //立项策划信息
        PlotInfo plotInfo = plotInfoDao.queryByProCode(plotDetail.getProCode());
        if (plotInfo != null) {
            PlotInfoVo piv = new PlotInfoVo();
            piv.setOptRemark(plotInfo.getOptRemark());
            piv.setCsResult(plotInfo.getCsResult());
            if (StringUtils.isNotBlank(plotInfo.getCsBoundJson())) {
                List<PlotTableVo> plotTableList = JSON.parseArray(plotInfo.getCsBoundJson(), PlotTableVo.class);
                piv.setPlotTableDatas(plotTableList);
            }
            setupJson.setPlotInfo(piv);
        }
        //附件信息表
        List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(plotDetail.getProCode(), ProjectFileTypeEnum.FILE_TYPE1.getCode(), null);
        setupJson.setFileAtt(fileAttaListToArray(projectAttaList));
        //合作单位信息
        List<CoopInfo> coopInfoList = coopInfoService.queryByTypes(CoopInfoTypesEnums.OWNER, 1);
        setupJson.setCoopInfoList(coopInfoList);
        return setupJson;
    }

    @Override
    public String[] fileAttaListToArray(List<ProjectAttachment> list) {
	    if (list == null || list.size() <= 0) return null;
	    String[] attaArr = new String[list.size()];
	    int index = 0;
	    for (ProjectAttachment pa : list) {
	        StringBuffer tmp = new StringBuffer();
	        tmp.append(pa.getSubTypes());
	        tmp.append("|");
	        tmp.append(pa.getFileName());
	        tmp.append(pa.getFileSuffix());
	        tmp.append("|");
	        tmp.append(IdFactory.getUUIDSerialNumber());
	        tmp.append("|");
	        tmp.append(pa.getFilePath());
	        attaArr[index] = tmp.toString();
	        index++;
        }
	    return attaArr;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo editSetupProDetail(ProjectInfo proInfo, SetupPro setupPro, List<AfterSummaryCoop> summCoopList,
                                    ProjectSubInfo proSubInfo, List<ProjectRisk> riskList, PlotInfo plotInfo,
                                    List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
        //根据pro_code查询项目基础信息
	    ProjectInfo tmpProInfo = projectInfoDao.findByProCode(proInfo.getProCode());
        if (tmpProInfo == null) return RspVo.getFailureResponse(400, "项目基础信息不存在");
        SetupPro tmpSp = setupProDao.selectByPrimaryKey(setupPro.getId());
        if (tmpSp == null) return RspVo.getFailureResponse(400, "立项信息不存在");
        //判断审批状态
        if (StringUtils.isNotBlank(tmpSp.getProcessStatus())
                && (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpSp.getProcessStatus())
                || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpSp.getProcessStatus()))) {
            return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
        }

        proInfo.setId(tmpProInfo.getId());
        proInfo.setUptBy(vo.getId());
        proInfo.setUptTime(new Date());
        proInfo.setProFormat(null);
        //更新项目基础信息
        projectInfoDao.modifyProjectInfoBySeletive(proInfo);

        //更新立项信息
        setupProDao.modifySetupProById(setupPro);

        //更新项目合作单位
//        afterSummaryCoopDao.deleteByProCode(proInfo.getProCode());
        if (summCoopList!=null && summCoopList.size()>0){
            afterSummaryCoopDao.deleteSetupCoopByProCode(proInfo.getProCode());
            afterSummaryCoopDao.insertByBatch(summCoopList);
        }
        //更新子项表格信息数据
        ProjectSubInfo psi = projectSubInfoDao.queryByProCode(proInfo.getProCode());
        if (psi == null) {
            proSubInfo.setAddBy(vo.getId());
            proSubInfo.setAddTime(new Date());
            projectSubInfoDao.insert(proSubInfo);
        } else {
            proSubInfo.setId(psi.getId());
            projectSubInfoDao.modifyById(proSubInfo);
        }

        //更新风险信息
        if (riskList != null && riskList.size() > 0) {
//            projectRiskDao.deleteByProCode(proInfo.getProCode());
            projectRiskDao.insertBatch(riskList);
        }

        //更新立项策划信息
        PlotInfo tmpPi = plotInfoDao.queryByProCode(proInfo.getProCode());
        if (tmpPi == null) {
            plotInfo.setAddBy(vo.getId());
            plotInfo.setAddTime(new Date());
            plotInfoDao.insert(plotInfo);
        } else {
            plotInfo.setId(tmpPi.getId());
            plotInfoDao.modifyPlotInfoById(plotInfo);
        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(proInfo.getProCode(), ProjectFileTypeEnum.FILE_TYPE1.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }

        if (submitType == 1) {
            if (StringUtils.isNotBlank(tmpSp.getOaId())) {
                oaFlowService.finishOA(tmpSp.getOaId());
            }
            String detailJson = JSON.toJSONString(queryDetailById(setupPro.getId()));
            proProcessManageService.sendProcess(ProProcessDetailTypeEnum.PRO_NODE_TYPE2, detailJson, setupPro.getId(), proInfo.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();
    }

    @Override
    public List<MktSetupProInfo> queryPublicProInfo() {
        return setupProDao.queryPublicProInfo();
    }

    @Override
    public List<MktSetupProInfo> getProjectBudgetMktList() {
        return setupProDao.getProjectBudgetMktList();
    }
}
